package com.sw.haruka.module.ftp

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.fragment.app.Fragment
import com.sw.haruka.R
import com.sw.haruka.dal.HarukaConfig
import com.sw.haruka.helper.utils.ActivityUtils
import com.sw.haruka.helper.utils.NetUtils
import com.sw.haruka.module.ftp.manager.FtpServerManager
import com.sw.haruka.module.ftp.viewmodel.FtpAction
import com.sw.haruka.ui.widget.PageWithBack

class FTPFragment : Fragment(), FtpServerManager.FtpObserver {

    private var ftpAction: FtpAction? = null
    private val serverStatusState = mutableStateOf("")
    private val serverSwitchState = mutableStateOf(false)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        FtpServerManager.getInstance().addObserver(this)
        ftpAction = object : FtpAction {
            override fun startServer(): Boolean {
                try {
                    FtpServerManager.getInstance().start(HarukaConfig.ROOT_PATH)
                    return true
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                return false
            }

            override fun stopServer(): Boolean {
                try {
                    FtpServerManager.getInstance().stop()
                    return true
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                return false
            }

        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = ComposeView(requireContext()).apply {
        setContent {
            val serverStatus by remember { serverStatusState }

            PageWithBack(title = "FTP", backClickListener = {
                ActivityUtils.mainActivity?.get()?.exitFragment()
            }) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(dimensionResource(id = R.dimen.ftpContentPadding))
                ) {
                    Column(modifier = Modifier.align(Alignment.Center)) {
                        //Server status
                        if (serverStatus.isNotEmpty()) {
                            ServerStatus(status = serverStatus)
                            Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.ftpServerStatusBottomMargin)))
                        }
                        //Switch buttons
                        Switch(serverSwitchState) {
                            if (it) {
                                ftpAction?.startServer()
                            } else {
                                ftpAction?.stopServer()
                            }
                        }
                    }
                    //Notice
                    Column(modifier = Modifier.align(Alignment.BottomCenter)) {
                        Notice()
                        Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.ftpNoticeBottomMargin)))
                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        statusChange(FtpServerManager.getInstance().isOpen)
    }

    override fun statusChange(offset: Boolean) {
        serverStatusState.value = if (offset) {
            getString(R.string.ftpServerStatusStarted, NetUtils.getLocalIP(context), FtpServerManager.getInstance().port)
        } else {
            getString(R.string.ftpServerStatusStopped)
        }
        serverSwitchState.value = offset
    }

    override fun onDestroy() {
        super.onDestroy()
        FtpServerManager.getInstance().removeObserver(this)
    }

}

@Composable
private fun Notice() {
    Text(text = stringResource(id = R.string.ftp_act_notice))
}


@SuppressLint("UnrememberedMutableState")
@Preview
@Composable
private fun Test() {
    ServerStatus(status = "未连接\n123.123.123")
}

@Composable
private fun ServerStatus(status: String) {
    Text(
        modifier = Modifier.fillMaxWidth(),
        color = colorResource(id = R.color.ftpServerStatusColor),
        textAlign = TextAlign.Center,
        text = status
    )
}

@Composable
private fun Switch(offOn: MutableState<Boolean>, clickEvent: (offOn:Boolean)->Unit) {
    var localOffOn by remember { offOn }
    if (localOffOn) {
        Button(
            modifier = Modifier.fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(
                backgroundColor = colorResource(id = android.R.color.holo_red_dark),
                contentColor = colorResource(id = android.R.color.holo_red_dark)
            ),
            shape = RoundedCornerShape(dimensionResource(id = R.dimen.ftpButtonCornerWidth)),
            border = BorderStroke(
                width = dimensionResource(id = R.dimen.ftpButtonBorderWidth),
                color = colorResource(id = android.R.color.holo_red_dark)
            ),
            onClick = {
                localOffOn = false
                clickEvent(false)
            }
        ) {
            Text(
                color = colorResource(id = R.color.ftp_button_text_stop),
                text = stringResource(id = R.string.ftp_button_text_stop)
            )
        }
    } else {
        Button(
            modifier = Modifier.fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(
                backgroundColor = colorResource(id = android.R.color.white),
                contentColor = colorResource(id = android.R.color.white)
            ),
            shape = RoundedCornerShape(dimensionResource(id = R.dimen.ftpButtonCornerWidth)),
            border = BorderStroke(
                width = dimensionResource(id = R.dimen.ftpButtonBorderWidth),
                color = colorResource(id = android.R.color.holo_red_dark)
            ),
            onClick = {
                localOffOn = true
                clickEvent(true)
            }
        ) {
            Text(
                color = colorResource(id = R.color.ftp_button_text_start),
                text = stringResource(id = R.string.ftp_button_text_start)
            )
        }
    }
}
